<template>
  <div class="page">
    <div class="tab1">
      <el-menu class="el-menu-vertical-demo" text-color="#fff" @select="select">
        <el-menu-item index="1">
          <i class="el-icon-menu"></i>
          <span slot="title">基于Theil-Sen趋势分析</span>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-document"></i>
          <span slot="title">叠加Hurst指数预测未来变化</span>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="doBuffer">
      <el-button plain @click="doPointsBuffer">建立缓冲区</el-button>
    </div>
    <div class="doBufferQuery">
      <el-button plain @click="bufferQuery">缓冲区查询</el-button>
    </div>
    <div class="clearAll">
      <el-button plain @click="clearAll">清空图层</el-button>
    </div>
    <div class="selectTrend">
      <el-select
        @change="valueChange"
        v-model="value"
        size="medium"
        placeholder="请选择变化"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
    <div class="ganjiangMap"><ArcgisMap ref="map_ref"></ArcgisMap></div>
    <!-- 图表 -->
    <div class="chartbox" v-show="chartvisable">
      <div ref="chart_ref" class="chart"></div>
      <div class="box-bottom"></div>
    </div>
    <!-- 文本 -->
    <el-popover
      v-if="index"
      trigger="hover"
      placement="left-start"
      title=""
      width="840"
    >
      <img
        width="400px"
        height="500px"
        src="../assets/NPP未来变化趋势.jpg"
        alt=""
      />
      <img
        width="400px"
        height="500px"
        src="../assets/赣江流域NPP变化趋势.jpg"
        alt=""
      />
      <div v-if="index === '1'" slot="reference" class="msgbox">
        <div class="msg">
          <h3>基于Theil-Sen趋势分析</h3>
          <hr />
          <p>
            NPP 显著增加的区域面积占比最高为 40.39%，主要位于赣江
            流域上游兴国县、于都县以及中游吉安县、下游高安市、樟树市等地;
          </p>
          <hr />
          <p>不显著增加区域面积占22.33%，上、中、下皆有分布;</p>
          <hr />
          <p>显著减少区域面积占7.21%，主要分布于赣州、宜春市区周围。</p>
          <hr />
          <p>
            不显著减少区域面积占
            30.07%，主要分布在上游崇义县、全南县以及中游井冈山市等地;
          </p>
        </div>
        <div class="box-bottom"></div>
      </div>
      <div v-if="index === '2'" slot="reference" class="msgbox">
        <div class="msg">
          <h3>叠加Hurst指数预测未来NPP变化</h3>
          <hr />
          <p>
            持续改善的区域占28.35%; 上游兴国县、信丰县地区,
            中游吉安县、安福县东部以及永丰县北部地区,
            下游广泛分布于宜春市区、高安市、丰城市等地
          </p>
          <hr />
          <p>
            持续退化的区域占4.16%;
            主要分布于宁都县西部、井冈山市部分地区将持续退化。
          </p>
          <hr />
          <p>
            由改善到退化区域占12.35%; 主要分布在樟树市西部、泰和县与永新县地区。
          </p>
          <hr />
          <p>由退化到改善的区域占4.60%; 不显著变化区域占50.54%</p>
        </div>
        <div class="box-bottom"></div>
      </div>
    </el-popover>
  </div>
</template>

<script>
import ArcgisMap from "@/components/arcgisMap.vue";
import GeoJSONLayer from "@arcgis/core/layers/GeoJSONLayer";
import * as GeometryEngine from "@arcgis/core/geometry/geometryEngine.js";
import Graphic from "@arcgis/core/Graphic.js";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer.js";
import SimpleFillSymbol from "@arcgis/core/symbols/SimpleFillSymbol.js";
import SimpleLineSymbol from "@arcgis/core/symbols/SimpleLineSymbol.js";
import SimpleRenderer from "@arcgis/core/renderers/SimpleRenderer.js";
import Point from "@arcgis/core/geometry/Point.js";
import Query from "@arcgis/core/rest/support/Query";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
export default {
  components: {
    Map,
    ArcgisMap,
  },
  data() {
    return {
      activeIndex: "/trend", //活动视图
      map: null,
      options: [],
      value: "",
      index: "",
      chartInstance: {},
      SenName: ["显著减少", "不显著减少", "不显著增加", "显著增加"],
      upSenData: [0.08139, 0.3686, 0.20896, 0.34105],
      middleSenData: [0.07913, 0.32525, 0.20382, 0.3918],
      downSenData: [0.04529, 0.13631, 0.2746, 0.5438],
      allSenData: [0.07214, 0.30066, 0.22334, 0.40386],
      HurstName: [
        "持续退化",
        "由退化到改善",
        "不显著变化",
        "持续改善",
        "由改善到退化",
      ],
      upHurstData: [0.05, 0.04, 0.57, 0.23, 0.11],
      middleHurstData: [0.05, 0.04, 0.52, 0.26, 0.13],
      downHurstData: [0.02, 0.03, 0.41, 0.4, 0.14],
      allHurstData: [0.04, 0.04, 0.52, 0.28, 0.12],
      areaName: ["赣江上游", "赣江中游", "赣江下游", "全流域"],
      points: [], //点
      chartvisable: false,
      bufferLayer: [],
      buffers: [],
      view: null,
      featureCount: 0,
      allFeatures: [],
      queryResult: [],
    };
  },
  created() {
    //拿到view
    this.$bus.$on("arcgis-view-created", (view) => {
      this.view = view;
    });
  },
  mounted() {
    this.addGanJiangVec();
    // this.bufferQuery();
    // this.doPointsBuffer();
  },
  methods: {
    valueChange() {
      let color;
      // console.log(this.value);

      if (
        this.value === "显著减少" ||
        this.value === "持续退化" ||
        this.value === "由改善到退化"
      ) {
        color = [207, 0, 13];
      } else if (
        this.value === "显著增加" ||
        this.value === "持续改善" ||
        this.value === "由退化到改善"
      ) {
        color = [74, 159, 9];
      } else {
        color = [13, 161, 248];
      }
      //移除之前的缓冲区
      if (this.bufferLayer.length) {
        this.$refs.map_ref.map.layers.remove(this.bufferLayer[0]);
        this.bufferLayer.length = 0; //清空
      }
      //移除之前的缓冲区
      if (this.buffers.length) {
        this.buffers.length = 0;
      }
      if (this.featureCount) {
        this.featureCount = 0;
      }
      if (this.queryResult) {
        this.view.map.layers.items.forEach((e) => {
          if (e.type === "feature") {
            this.view.map.remove(e);
          }
        });
      }
      this.addPoints(this.value, color);
    },
    async addPoints(value, color) {
      //移除之前的点
      if (this.points.length) {
        this.$refs.map_ref.map.layers.remove(this.points[0]);
        this.points.length = 0; //清空
      }
      //赣江流域
      const ganjiang = (
        await this.axios.get(`/static/geojson/geojson2/ganjiang.json`)
      ).data;
      // console.log(ganjiang.features[0].geometry);
      //添加新点
      const points = new GeoJSONLayer({
        url: `static/geojson/geojson2/${value}.json`,
        title: `${value}`,
        outFields: ["*"], //属性
        popupTemplate: {
          title: "{type}",
          content: [
            {
              type: "fields",
              fieldInfos: [
                {
                  fieldName: "address",
                  label: "所在地",
                  visible: true,
                  format: {
                    places: 0,
                    digitSeparator: true,
                  },
                },
                {
                  fieldName: "longitude",
                  label: "经度",
                },
                {
                  fieldName: "latitude",
                  label: "纬度",
                },
              ],
            },
          ],
        },
        renderer: {
          type: "simple",
          symbol: {
            type: "simple-marker",
            size: 10,
            color: color,
          },
        },
      });
      await this.$refs.map_ref.map.layers.add(points);
      this.points.push(points); //缓存
      // this.doPointsBuffer(value);
    },
    select(index, path) {
      this.chartvisable = true;
      if (index === "1") {
        this.index = index;
        //显示图表信息
        this.$nextTick(() => {
          this.SenChartInit();
          this.SenAnalysis();
        });
      } else if (index === "2") {
        this.index = index;
        this.$nextTick(() => {
          this.HurstChartInit();
          this.HurstAnalysis();
        });
      }
    },
    SenAnalysis() {
      const Senoptions = [
        {
          value: "显著减少",
        },
        {
          value: "不显著减少",
        },
        {
          value: "不显著增加",
        },
        {
          value: "显著增加",
        },
      ];
      this.options = Senoptions;
    },
    HurstAnalysis() {
      const Hurstoptions = [
        {
          value: "持续退化",
        },
        {
          value: "由退化到改善",
        },
        {
          value: "不显著变化",
        },
        {
          value: "持续改善",
        },
        {
          value: "由改善到退化",
        },
      ];
      this.options = Hurstoptions;
    },
    //获取赣江流域30km内的城市名与坐标
    async getCoordinates() {
      const features = (
        await this.axios.get(
          `/static/geojson/geojson_30km/${this.value}30km.json`
        )
      ).data.features;
      const corrd = features.map((item) => {
        const arr = [
          item.geometry.coordinates[0],
          item.geometry.coordinates[1],
        ];
        const cityname = item.properties.name;
        const cities = {
          name: cityname,
          coordinates: arr,
        };
        return cities;
      });
      return corrd;
    },
    //雷达图
    SenChartInit() {
      //初始化图表
      this.chartInstance = this.$echarts.init(this.$refs.chart_ref, "dark");
      const op = {
        backgroundColor: "rgba(0, 0, 0, 0)",
        color: ["#FF6B6B", "#4ECDC4", "#FFBE0B", "#8338EC", "#3A86FF"],
        title: {
          text: "近20年变化特征",
          top: "1%",
          left: "center",
        },
        tooltip: {
          //触发条件，鼠标移入坐标轴
          trigger: "item",
          //高亮类型
          axisPointer: {
            //线条
            type: "line",
            z: 0,
            lineStyle: {
              type: "solid",
              color: "#2D3443",
            },
          },
          backgroundColor: "rgba(16,12,42,0.9)",
          textStyle: {
            color: "#fff",
          },
        },
        legend: {
          data: this.areaName,
          bottom: "2%",
          itemGap: 10,
        },
        radar: [
          {
            indicator: [
              { name: "显著减少", max: 0.6 },
              { name: "不显著减少", max: 0.6 },
              { name: "不显著增加", max: 0.6 },
              { name: "显著增加", max: 0.6 },
            ],
            radius: "75%",
            center: ["50%", "50%"],
            startAngle: 135,
            name: {
              textStyle: {
                color: "#1883ff",
              },
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            axisLine: {
              show: true,
              symbol: "arrow",
              symbolSize: [5, 7.5],
              lineStyle: {
                color: "#1883ff",
                type: "dashed",
              },
            },
            splitArea: {
              show: false,
            },
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            type: "radar",
            areaStyle: {},
            symbol: "none",
            itemStyle: {
              normal: {
                areaStyle: {
                  type: "default",
                },
              },
            },
            lineStyle: {
              opacity: 0,
            },
            data: [
              {
                value: this.upSenData,
                name: "赣江上游",
              },
              {
                value: this.middleSenData,
                name: "赣江中游",
              },
              {
                value: this.downSenData,
                name: "赣江下游",
              },
              {
                value: this.allSenData,
                name: "全流域",
              },
            ],
          },
        ],
      };
      this.chartInstance.setOption(op);
    },
    HurstChartInit() {
      //初始化图表
      this.chartInstance = this.$echarts.init(this.$refs.chart_ref, "dark");
      const option = {
        backgroundColor: "rgba(0, 0, 0, 0)",
        color: ["#FDC5F5", "#F45B69", "#F7A072", "#B5EAD7", "#06D6A0"],
        title: {
          text: "未来变化预测",
          top: "1%",
          left: "center",
        },
        //高亮显示
        tooltip: {
          //触发条件，鼠标移入坐标轴
          trigger: "item",
          //高亮类型
          axisPointer: {
            //线条
            type: "line",
            z: 0,
            lineStyle: {
              type: "solid",
              color: "#2D3443",
            },
          },
          backgroundColor: "rgba(16,12,42,0.9)",
          textStyle: {
            color: "#fff",
          },
        },
        legend: {
          data: this.areaName,
          bottom: "2%",
          itemGap: 10,
        },
        radar: {
          radius: "75%",
            center: ["50%", "50%"],
            startAngle: 45,
            name: {
              textStyle: {
                color: "#1883ff",
              },
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            axisLine: {
              show: true,
              symbol: "arrow",
              symbolSize: [5, 7.5],
              lineStyle: {
                color: "#1883ff",
                type: "dashed",
              },
            },
            splitArea: {
              show: false,
            },
            splitLine: {
              show: false,
            },
          indicator: [
            { name: "持续退化", max: 0.2 },
            { name: "由退化到改善", max: 0.2 },
            { name: "不显著变化", max: 0.6 },
            { name: "持续改善", max: 0.6 },
            { name: "由改善到退化", max: 0.2 },
          ],
        },
        series: [
          {
            name: "占比",
            type: "radar",
            areaStyle: {},
            symbol: "none",
            itemStyle: {
              normal: {
                areaStyle: {
                  type: "default",
                },
              },
            },
            lineStyle: {
              opacity: 0,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: "bold",
              },
            },
            data: [
              {
                value: this.upHurstData,
                name: "赣江上游",
              },
              {
                value: this.middleHurstData,
                name: "赣江中游",
              },
              {
                value: this.downHurstData,
                name: "赣江下游",
              },
              {
                value: this.allHurstData,
                name: "全流域",
              },
            ],
          },
        ],
      };
      this.chartInstance.setOption(option);
    },
    //添加赣江矢量
    async addGanJiangVec() {
      const ganjiang = new GeoJSONLayer({
        url: "static/geojson/geojson2/ganjiang.json",
        title: "赣江流域",
        outFields: ["*"], //属性
        renderer: {
          type: "simple",
          symbol: {
            type: "simple-fill",
            color: "rgba(150,150,150,0.2)",
            outline: {
              width: 0.7,
              color: [150, 150, 150],
            },
          },
        },
      });
      await this.$refs.map_ref.map.layers.add(ganjiang);
    },
    //点缓冲区建立
    async doPointsBuffer() {
      if (!this.value) {
        this.$message.error("请选择变化数据");
        return;
      }
      //移除之前的缓冲区
      if (this.bufferLayer.length) {
        this.$refs.map_ref.map.layers.remove(this.bufferLayer[0]);
        this.bufferLayer.length = 0; //清空
      }
      const points = await this.returnPoints(this.value);
      const graphicsLayer = new GraphicsLayer({
        id: "bufferLayer",
      });
      this.$refs.map_ref.map.add(graphicsLayer);
      //建立缓冲区
      points.forEach((pt) => {
        const bufferGeometry = GeometryEngine.buffer(pt, 20000, "meters");
        this.buffers.push(bufferGeometry);
        // 将缓冲区显示为图形
        const bufferGraphic = new Graphic({
          geometry: bufferGeometry,
          symbol: {
            type: "simple-fill",
            color: [255, 0, 0, 0.5],
            outline: {
              color: [255, 0, 0],
              width: 1,
            },
          },
        });
        graphicsLayer.add(bufferGraphic);
        // this.bufferQuery(bufferGeometry);
      });
      this.bufferLayer.push(graphicsLayer);
    },
    //返回点集
    async returnPoints(value) {
      const trend = (
        await this.axios.get(`/static/geojson/geojson2/${value}.json`)
      ).data;
      // console.log(不显著变化.features);
      const pointsFeatures = trend.features;
      const points = [];
      pointsFeatures.forEach((pt) => {
        // console.log(pt.geometry.coordinates);
        // 创建点缓冲区
        const point = new Point({
          type: "point",
          longitude: pt.geometry.coordinates[0],
          latitude: pt.geometry.coordinates[1],
          spatialReference: { wkid: 3857 },
        });
        points.push(point);
      });
      return points;
    },
    //缓冲区查询
    async bufferQuery() {
      //判断
      if (this.buffers.length === 0 || this.bufferLayer.length === 0) {
        this.$message.error("请先建立缓冲区");
      } else {
        // 清除之前的查询结果
        this.featureCount = 0;
        this.allFeatures = []; // 清空要素数组

        // 移除之前的高亮图层
        if (this.queryResult && this.queryResult.length > 0) {
          this.queryResult.forEach((layer) => {
            this.view.map.remove(layer);
          });
          this.queryResult = []; // 清空图层缓存
        }
        const ganjiang = new FeatureLayer({
          url: "",
          outFields: ["*"],
        });
        // 等待源图层加载
        await ganjiang.load();
        // console.log("源图层加载成功，几何类型:", ganjiang.geometryType);
        // 定义高亮符号
        const highlightSymbol = new SimpleFillSymbol({
          color: [155, 155, 0, 0.3], // 黄色半透明填充
          outline: new SimpleLineSymbol({
            color: [155, 155, 0],
            width: 1,
          }),
        });
        //查询
        const queryPromises = this.buffers.map((b) =>
          ganjiang.queryFeatures(
            new Query({
              geometry: b,
              spatialRelationship: "intersects",
              outFields: ["*"],
              returnGeometry: true,
              outSpatialReference: { wkid: 3857 },
            })
          )
        );
        // 使用Promise.all和flatMap简化结果处理
        const results = await Promise.all(queryPromises);
        this.allFeatures = results.flatMap((result) => result.features);
        this.featureCount = this.allFeatures.length;

        await Promise.all(queryPromises)
          .then(async () => {
            if (this.allFeatures.length === 0) {
              this.$message.warning("未查询到任何要素");
              return;
            }
            let highlightLayer = new FeatureLayer({
              title: "查询结果",
              source: this.allFeatures,
              objectIdField: "fid", // 根据实际数据调整
              fields: ganjiang.fields, // 将在查询后填充
              geometryType: "polygon", // 根据实际几何类型调整
              spatialReference: { wkid: 3857 },
              renderer: new SimpleRenderer({
                symbol: highlightSymbol,
              }),
              popupTemplate: {
                title: "{name}",
                // content: 根据需要添加内容
              },
            });
            this.view.map.add(highlightLayer);
            //缓存
            this.queryResult.push(highlightLayer);
            this.$message.success(`共查询到${this.featureCount}条数据。`);
            // 6. 缩放到查询结果
            const extent = this.allFeatures.reduce((acc, feature) => {
              return acc
                ? acc.union(feature.geometry.extent)
                : feature.geometry.extent;
            }, null);

            if (extent) {
              this.view.goTo(extent);
            }
          })
          .catch((error) => {
            console.error("查询出错:", error);
            this.$message.error("查询失败");
          });
      }
    },
    //清空图层
    clearAll() {
      this.value = "";
      this.view.map.layers.removeAll();
    },
  },
};
</script>

<style scoped>
.el-menu-item {
  font-size: 18px;
}
.el-menu-vertical-demo {
  background-color: rgba(0, 0, 0, 0);
}
.el-menu-item:focus,
.el-menu-item:hover {
  outline: 0;
  background-color: rgba(255, 255, 255, 0.2);
}
.ganjiangMap {
  position: absolute;
  top: 0%;
  left: 20%;
  width: 50%;
  height: 100%;
  z-index: 1;
}
.tab1 {
  position: absolute;
  left: 0%;
  top: 1%;
  width: 20%;
  /* border: 3px solid #9CDCFE; */
  border-radius: 5px;
  padding: 10px 0px;
}
.selectTrend {
  position: absolute;
  top: 25%;
  left: 2%;
}
.doBuffer {
  position: absolute;
  top: 35%;
  left: 4%;
}
.doBufferQuery {
  position: absolute;
  top: 45%;
  left: 4%;
}
.clearAll {
  position: absolute;
  top: 55%;
  left: 4%;
}
.chartbox {
  padding: 4px;
  position: absolute;
  bottom: 2%;
  right: 1%;
  width: 28%;
  height: 53%;
  z-index: 1;
}
.chartbox::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  border-top: 4px solid #98e9d1;
  border-right: 4px solid #98e9d1;
  z-index: 1;
}
.chartbox::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
  border-top: 4px solid #98e9d1;
  border-left: 4px solid #98e9d1;
  z-index: 1;
}
.chart {
  width: 100%;
  height: 100%;
}
.msgbox {
  padding: 2px 10px;
  position: absolute;
  top: 1%;
  right: 1%;
  width: 28%;
  height: 42%;
  background-color: rgba(0, 0, 0, 0);
}
.msgbox::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  border-top: 4px solid #98e9d1;
  border-right: 4px solid #98e9d1;
  z-index: 1;
}
.msgbox::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
  border-top: 4px solid #98e9d1;
  border-left: 4px solid #98e9d1;
  z-index: 1;
}
.msg {
  width: 100%;
  height: 100%;
  color: rgb(154, 242, 219);
  /* z-index: 1; */
}
.msg h3 {
  text-align: center;
  font-size: 18px;
}
.msg p {
  font-size: 14px;
  font-weight: 500;
}
.msg hr {
  border: none;
  border-top: 1px solid #00ddff;
  width: 100%;
}
.box-bottom::before {
  content: "";
  position: absolute;
  bottom: 0;
  right: 0;
  width: 20px;
  height: 20px;
  border-bottom: 4px solid #98e9d1;
  border-right: 4px solid #98e9d1;
  z-index: 1;
}
.box-bottom::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 20px;
  height: 20px;
  border-bottom: 4px solid #98e9d1;
  border-left: 4px solid #98e9d1;
  z-index: 1;
}
</style>